import 'dart:math';

import 'package:flutter/material.dart' hide showSearch,Banner;
import 'package:flutter/cupertino.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_wan_android/config.dart';
import 'package:flutter_wan_android/entity/article_entity.dart';
import 'package:flutter_wan_android/manager/router_manger.dart';
import 'package:flutter_wan_android/provider/provider_widget.dart';
import 'package:flutter_wan_android/ui/search/home_search_delegate.dart';
import 'package:flutter_wan_android/ui/widget/article_list_Item.dart';
import 'package:flutter_wan_android/ui/widget/article_skeleton_item.dart';
import 'package:flutter_wan_android/view_model/tap_to_top_model.dart';
import 'package:flutter_wan_android/ui/widget/banner_image.dart';
import 'package:flutter_wan_android/view_model/home_model.dart';
import 'package:flutter_wan_android/widget/animated_switchers.dart';
import 'package:flutter_wan_android/widget/flutter/search.dart';
import 'package:flutter_wan_android/widget/refresh_helper.dart';
import 'package:flutter_wan_android/widget/skeleton.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var bannerHeight = MediaQuery.of(context).size.width * 5 / 11;
    return ProviderWidget2<HomeModel, TapToTopModel>(
        model1: HomeModel(),
        model2: TapToTopModel(PrimaryScrollController.of(context), height: bannerHeight - kToolbarHeight),
        onModelReady: (homeModel, tapToTopModel) {
          ///初始化数据
          homeModel.initData();
          tapToTopModel.init();
        },
        child: Scaffold(
          ///悬浮按钮
          floatingActionButton: Consumer<TapToTopModel>(builder: (context, tapToTopModel, child) {
            if (tapToTopModel.showTopBtn) {
              return FloatingActionButton(
                  child: Icon(Icons.vertical_align_top),
                  onPressed: () {
                    tapToTopModel.scrollToTop();
                  });
            } else {
              return FloatingActionButton(child: Icon(Icons.search), onPressed: () {
                showSearch(context: context, delegate: HomeSearchDelegate());
              });
            }
          }),
          body:

              ///当前的Selector只用于提供TapToTopModel对象
              ///所以当TapToTopModel变化时，并不会引起页面的刷新
              Selector<TapToTopModel, TapToTopModel>(
                  selector: (context, tapToTopModel) => tapToTopModel,
                  shouldRebuild: (previous, next) => false,
                  builder: (context, tapToTopModel, child) {
                    ///当前的Selector根据HomeModel状态重新构建
                    return Selector<HomeModel, HomeModel>(
                        shouldRebuild: (previous, next) => true,
                        selector: (context, homeModel) => homeModel,
                        builder: (context, homeModel, child) {
                          ///数据错误时显示错误界面
                          if (homeModel.isEmpty || homeModel.isError) {
                            return Center(
                                child: RaisedButton(
                              child: Text("重试"),
                              onPressed: () {
                                homeModel.refresh();
                              },
                            ));
                          }

                          ///显示正常加载列表
                          return RefreshConfiguration.copyAncestor(
                            context: context,

                            ///下拉触发二楼距离
                            twiceTriggerDistance: HomeRefreshHeight - 15,

                            ///最大下拉距离,android默认为0,这里为了触发二楼
                            maxOverScrollExtent: HomeRefreshHeight,
                            autoLoad: true,

                            ///头部触发刷新的越界距离
                            headerTriggerDistance: 80 + MediaQuery.of(context).padding.top / 3,
                            child: SmartRefresher(
                              controller: homeModel.refreshController,
                              header: HomeRefreshHeader(),
                              enablePullDown: true,
                              enablePullUp: homeModel.dataList.isNotEmpty,
                              onLoading: homeModel.loadMore,
                              onRefresh: () async {
                                await homeModel.refresh();
                                homeModel.showErrorMessage(context);
                              },

                              ///二楼设置
                              enableTwoLevel: homeModel.dataList.isNotEmpty,
                              onTwoLevel: () async {
                                await RoutesManager.getInstance().pushTwoLevelPage(context);
                                //await Future.delayed(Duration(milliseconds: 300));
                                homeModel.refreshController.twoLevelComplete();
                              },
                              child: CustomScrollView(
                                controller: tapToTopModel.scrollController,
                                slivers: <Widget>[
                                  ///根据TapToTopModel的变化动态生成SliverAppBar
                                  Selector<TapToTopModel, TapToTopModel>(
                                      selector: (context, tapToTopModel) => tapToTopModel,
                                      shouldRebuild: (previous, next) => true,
                                      builder: (context, tapToTopModel, child) {
                                        return SliverAppBar(
                                          /// 加载中并且亮色模式下,状态栏文字为黑色
                                          brightness: Theme.of(context).brightness == Brightness.light
                                              ? Brightness.dark
                                              : Brightness.light,

                                          /// 顶部搜索按钮
                                          actions: <Widget>[
                                            EmptyAnimatedSwitcher(
                                              display: tapToTopModel.showTopBtn,
                                              child: IconButton(
                                                icon: Icon(Icons.search),
                                                onPressed: () {
                                                  showSearch(context: context, delegate: HomeSearchDelegate());
                                                },
                                              ),
                                            ),
                                          ],

                                          /// 显示banner
                                          flexibleSpace: FlexibleSpaceBar(
                                            background: BannerWidget(),
                                            centerTitle: true,
                                            title: EmptyAnimatedSwitcher(
                                              display: tapToTopModel.showTopBtn,
                                              child: Text("Wan Android"),
                                            ),
                                          ),
                                          expandedHeight: bannerHeight,
                                          pinned: true,
                                        );
                                      }),

                                  ///加载新闻列表
                                  if (homeModel.isBusy)
                                    SliverToBoxAdapter(
                                        child: SkeletonList(builder: (context, index) => ArticleSkeletonItem()))
                                  else
                                    SliverList(
                                        delegate: SliverChildBuilderDelegate((context, index) {
                                      ArticleEntity articleEntity = homeModel.topArticles[index];
                                      return ArticleItemWidget(articleEntity, top: true);
                                    }, childCount: homeModel.topArticles.length)),

                                  ///加载新闻列表
                                  if (homeModel.isIdle)
                                    SliverList(
                                        delegate: SliverChildBuilderDelegate((context, index) {
                                      ArticleEntity articleEntity = homeModel.dataList[index];
                                      return ArticleItemWidget(articleEntity);
                                    }, childCount: homeModel.dataList.length))
                                ],
                              ),
                            ),
                          );
                        });
                  }),
        ));
  }
}

///
/// 顶部Banner
///
class BannerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
      ),
      child: Consumer<HomeModel>(builder: (_, homeModel, __) {
        if (homeModel.isBusy) {
          return CupertinoActivityIndicator();
        } else {
          var banners = homeModel?.banners ?? [];
          return Swiper(
            loop: true,
            autoplay: true,
            autoplayDelay: 5000,
            pagination: SwiperPagination(),
            itemCount: banners.length,
            itemBuilder: (ctx, index) {
              return InkWell(onTap: () {}, child: BannerImage(banners[index].imagePath));
            },
          );
        }
      }),
    );
  }
}
